package com.cheyunkeji.er.activity.evaluate;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;

public class PhotoPreViewActivity extends BaseActivity {


    private static final String TAG = PhotoPreViewActivity.class.getSimpleName();

    @BindView(R.id.v_topbar)
    TopBar vTopbar;
//    @BindView(R.id.btn_delete)
//    Button btnDelete;
    @BindView(R.id.iv_preview)
    ImageView ivPreview;
    @BindView(R.id.activity_photo_pre_view)
    LinearLayout activityPhotoPreView;
    private String imgPath;

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_photo_pre_view);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        vTopbar.setLeftBack();
        vTopbar.setRight("",R.drawable.er_icon_delete_dustbin,this);
        loadDialog.setCanceledOnTouchOutside(true);
        if(!getIntent().getBooleanExtra("SHOW_DELETE_BTN",true)){
            vTopbar.hideRight();
        }
    }

    @Override
    public void onBackPressed() {
        if( loadDialog.isShowing() ){
            dismissDialog();
        }else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null != loadDialog) {
            loadDialog.setCanceledOnTouchOutside(false);
            loadDialog = null ;
        }
    }

    @Override
    protected void initData() {
        imgPath = getIntent().getStringExtra("IMG_PATH");
        if (!TextUtils.isEmpty(imgPath)) {
            showDialog();
            final Uri uri;
            if (imgPath.startsWith("http")) {
                uri = Uri.parse(imgPath);
            } else {
                uri = Uri.fromFile(new File(imgPath));
            }
            Glide.with(this).load(uri)
                    .thumbnail(0.1f)
                    .dontAnimate()
                    .dontTransform()
                    .override(800, 800)
                    .placeholder(me.iwf.photopicker.R.drawable.__picker_ic_photo_black_48dp)
                    .error(me.iwf.photopicker.R.drawable.__picker_ic_broken_image_black_48dp)
//                    设置Glide加载图片成功的监听
                    .into(new Target<Drawable>() {
                        @Override
                        public void onLoadStarted(@Nullable Drawable placeholder) {

                        }

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {

                        }

                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            ivPreview.setImageDrawable(resource);
                            dismissDialog();
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }

                        @Override
                        public void getSize(@NonNull SizeReadyCallback cb) {

                        }

                        @Override
                        public void removeCallback(@NonNull SizeReadyCallback cb) {

                        }

                        @Override
                        public void setRequest(@Nullable Request request) {

                        }

                        @Nullable
                        @Override
                        public Request getRequest() {
                            return null;
                        }

                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onStop() {

                        }

                        @Override
                        public void onDestroy() {

                        }
                    });

        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.vRight) {
//              删除OSS服务器图片
            if (!TextUtils.isEmpty(imgPath) && imgPath.startsWith("http://")) {
                showDialog();
                deleteImg(imgPath.substring(imgPath.lastIndexOf("/") + 1));
            } else {
//              删除本地图片，直接将图片链接置空
                Intent intent = new Intent();
                intent.putExtra("DELETE_IMG", true);
                setResult(RESULT_OK, intent);
                MyApplication.getInstance().removeActivity(PhotoPreViewActivity.class);
                finish();
            }
        }
    }


    /**
     * 删除图片
     *
     * @param imgPath
     */
    private void deleteImg(String imgPath) {
        // 创建删除请求
        DeleteObjectRequest delete = new DeleteObjectRequest(HttpConstants.ALIYUN_OSS_BUCKET, imgPath);
        // 异步删除
        OSSAsyncTask deleteTask = MyApplication.getInstance().getOss().asyncDeleteObject(delete, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
                    @Override
                    public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
                        SToast.show("删除成功！");
                        dismissDialog();

                        Intent intent = new Intent();
                        intent.putExtra("DELETE_IMG", true);
                        setResult(RESULT_OK, intent);
                        MyApplication.getInstance().removeActivity(PhotoPreViewActivity.class);
                        finish();
                    }

                    @Override
                    public void onFailure(DeleteObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        if (serviceException != null) {
                            // 服务异常
                            Log.e("ErrorCode", serviceException.getErrorCode());
                            Log.e("RequestId", serviceException.getRequestId());
                            Log.e("HostId", serviceException.getHostId());
                            Log.e("RawMessage", serviceException.getRawMessage());
                        }

                        dismissDialog();
                        SToast.show("删除失败，请重试！");
                    }
                }
        );

    }
}
